package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;

import org.apache.dubbo.config.annotation.Reference;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.io.IOException;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private AddressService addressService;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return addressService.pageQuery(queryPageBean);
    }

    //根据id查询
    @RequestMapping("/findByid")
    public Result findByid(Integer id) {
        try {
            Address address = addressService.findById(id);
            return new Result(true, MessageConstant.QUERY_ADDRESS_SUCCESS, address);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ADDRESS_FAIL);
        }
    }

    //添加地址
    @RequestMapping("/add")
    public Result add(@RequestBody Map map) {
        try {
            //获得传过来的数据
            String add = (String) map.get("address");
            String lal = (String) map.get("lal");
            String[] split = lal.split(",");
            Address address = new Address();
            address.setAddress(add);
            address.setLng(split[0]);
            address.setLat(split[1]);
            addressService.add(address);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ADDRESS_FAIL);
        }
        return new Result(true, MessageConstant.ADD_ADDRESS_SUCCESS);
    }


    //删除地址
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            addressService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ADDRESS_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_ADDRESS_SUCCESS);
    }

    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<Address> list=  addressService.findAll();
            return new Result(true,MessageConstant.QUERY_ADDRESS_SUCCESS,list);
        }
        catch(Exception e) {
            return new Result(false,MessageConstant.QUERY_ADDRESS_FAIL);
        }
    }
}
